package com.hello;

import java.util.concurrent.*;

/**
 * 创建线程方式三
 * 1、实现Callable接口，重写call方法
 *
 * 模拟龟兔赛跑
 *
 */
public class RacerCallable implements Callable<Integer> {
    private String winner;// 胜利者

    @Override
    public Integer call() throws InterruptedException {

        for (int step=1; step<=100; step++) {
            // 模拟兔子睡觉
            if (Thread.currentThread().getName().equals("pool-1-thread-1") && step%10==0) {
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName()+"--->"+step);
            boolean flag = gameOver(step); // 判断比赛是否结束
            if (flag){
                return step;
            }
        }
        return null;
    }

    public boolean gameOver(int step) {
        if (winner != null) { // 判断是否有胜利者
            return true;
        } else {
            if (step == 100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is===>" + winner);
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        RacerCallable r = new RacerCallable();

        // 创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(2);

        // 提交执行
        Future<Integer> result1 = service.submit(r);
        Future<Integer> result2 = service.submit(r);

        // 获取结果
        Integer r1 = result1.get();
        Integer r2 = result2.get();
        System.out.println(r1 + "--->" + r2);

        // 关闭服务
        service.shutdownNow();
    }
}
